package org.miniframework.mvc.render;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.miniframework.mvc.RequestProcessorChain;

import java.io.PrintWriter;

/**
 * Json渲染器
 */
@Slf4j
public class JsonResultRender implements ResultRender{

    private Object result;

    public JsonResultRender(Object result) {
        this.result = result;
    }

    @Override
    public void render(RequestProcessorChain chain) throws Exception {
        chain.getResponse().setContentType("application/json");
        chain.getResponse().setCharacterEncoding("utf-8");
        // 响应流写入经过gson格式化之后的处理结果 try -catch-resource
        Gson gson = new Gson();
        try(PrintWriter writer = chain.getResponse().getWriter()) {
            writer.write(gson.toJson(this.result));
            writer.flush();
        }catch (Exception e){
            log.error("JsonResultRender : json writer is failed {} , can stream Exception or gson Exception", gson.toJson(result));
        }
    }
}
